<template>
    <div id="edit_menu">
        <div class="container">
            <div class="handle-box">
                <el-checkbox v-if="btnPermit" v-model="query.checked" @change="handleStatusChange">
                    <!-- 待审核 -->
                    {{ $t('m.daiShenHeTick') }}
                </el-checkbox>
                <!-- <el-button type="danger" style="margin-left:25.2px; margin-bottom:18px;" @click.native="handleDelete()">删除</el-button> -->
                <el-button type="primary" style="margin-left: 25.2px; margin-bottom: 18px" @click.native="handleRefresh()">刷新</el-button>
                <!-- <el-button type="default" style="margin-left:25.2px; margin-bottom:18px;" @click.native="handleImport()"
                    >导入Excel</el-button
                > -->
                <el-form ref="form" :inline="true" :model="form">
                    <el-form-item label="">
                        <el-input
                            placeholder="ID"
                            clearable
                            @clear="handleSearch"
                            @keyup.native.enter="handleSearch"
                            v-model="query.id"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            @keyup.native.enter="handleSearch"
                            clearable
                            @clear="handleSearch"
                            v-model="query.name"
                            placeholder="名称"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            @keyup.native.enter="handleSearch"
                            clearable
                            @clear="handleSearch"
                            v-model="query.tagName"
                            placeholder="标签"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="" v-if="admin">
                        <el-input
                            @keyup.native.enter="handleSearch"
                            clearable
                            @clear="handleSearch"
                            v-model="query.createBy"
                            placeholder="创建者"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-select
                            v-model="query.excellentFlag"
                            placeholder="是否精品"
                            @change="handleSearch"
                            :clearable="true"
                            class="handle-select mr10"
                        >
                            <el-option key="1" label="是" :value="1"></el-option>
                            <el-option key="0" label="否" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-select
                            v-model="query.status"
                            @change="handleSearch"
                            placeholder="状态"
                            :clearable="true"
                            class="handle-select mr10"
                        >
                            <el-option key="0" label="下线" value="0"></el-option>
                            <el-option key="1" label="上线" value="1"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button :disabled="disabled" type="primary" @click="handleSearch">
                            <!-- 查询 -->
                            {{ $t('m.queryBtn') }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="ID" align="center">
                    <template slot-scope="scope">{{ scope.row.id }}</template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="externalId" align="center">
                    <template slot-scope="scope">{{ scope.row.externalId }}</template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="名称" align="center">
                    <template slot-scope="scope">{{ scope.row.name }}</template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="标签" align="center">
                    <template slot-scope="scope">{{ scope.row.tblTags ? scope.row.tblTags.name : '' }}</template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="是否精品" align="center">
                    <template slot-scope="scope">{{
                        scope.row.excellentFlag === true ? '是' : scope.row.excellentFlag === false ? '否' : ''
                    }}</template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="歌曲数量" align="center" prop="songCount">
                    <template slot-scope="scope">
                        <font color="#f00" v-if="scope.row.songCount < 10">{{ scope.row.songCount }}</font>
                        <font color="#606266" v-else>{{ scope.row.songCount }}</font>
                        <!-- {{  scope.row.songCount }} -->
                    </template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="昨日下线" align="center">
                    <template slot-scope="scope">{{ scope.row.yestOffCount }}</template>
                </el-table-column>

                <el-table-column v-if="query.checked === true" width="auto" label="状态" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.status == 0 ? '下线' : scope.row.status == 1 ? '上线' : '待上线' }}
                    </template>
                </el-table-column>

                <el-table-column v-if="query.checked === false" width="auto" label="状态" align="center">
                    <template slot-scope="scope">
                        <el-select
                            v-model="scope.row.status"
                            @change="handleChangeStatus($event, scope.$index, scope.row)"
                            placeholder=""
                            style="width: auto"
                        >
                            <el-option key="1" label="下线" :value="0"></el-option>
                            <el-option key="2" label="上线" :value="1"></el-option>
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="创建者" align="center">
                    <template slot-scope="scope">{{ scope.row.createBy }}</template>
                </el-table-column>

                <el-table-column :show-overflow-tooltip="true" width="auto" label="创建时间" align="center">
                    <template slot-scope="scope">{{ scope.row.createTime }}</template>
                </el-table-column>

                <el-table-column width="auto" label="管理" align="center">
                    <template slot-scope="scope">
                        <el-button
                            :type="'primary'"
                            v-if="!query.show"
                            :disabled="scope.row.editFlag == -1"
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)"
                        >
                            <!-- 编辑 -->
                            {{ $t('m.editBtn') }}
                        </el-button>
                        <el-button v-if="query.show" type="warning" size="mini" @click="handleChecked(scope.$index, scope.row)"
                            >审核</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 30]"
                    @size-change="handleSizeChange"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
  import NProgress from 'nprogress';
  import { mapGetters, mapMutations, mapActions } from 'vuex';
  import { debounce, throttle } from '@/utils/utils.js';
  import axios from 'axios';
  export default {
      name: 'EditMenu',
      data() {
          return {
              btnPermit: JSON.parse(localStorage.getItem('roles')) ? JSON.parse(localStorage.getItem('roles')).includes('ADMIN') : false,
              disabled: false,
              admin: localStorage.getItem('roles') ? JSON.parse(localStorage.getItem('roles')).includes('ADMIN') : false,
              // query: {
              //     show: false,
              //     checked: false,
              //     pageIndex: 1,
              //     pageSize: 10,
              //     id: '',
              //     name: '',
              //     tagName: '',
              //     status: '',
              //     createBy: ''
              // },
              // tableData: [],
              // pageTotal: 0,

              // show: false,
              operator: localStorage.getItem('ms_username') || '',
              form: {}
          };
      },
      destroyed() {
          if (!this.tagsList.some((item) => item.name === 'EditMenu')) {
              this.SET_EDITMENU_DATA([]);
              this.SET_EDITMENU_PAGETOTAL(0);
              this.SET_EDITMENU_QUERY({
                  checked: false,
                  pageIndex: 1,
                  pageSize: 10,
                  id: null,
                  name: null,
                  tagName: null,
                  status: null,
                  createBy: null,
                  excellentFlag: null
              });
              localStorage.removeItem('edit_menu_e');
              localStorage.removeItem('id_menu');
          } else {
              //  什么都不做
          }
      },
      // created() {
      //     if (this.query.checked === true) {
      //         if (this.tableData.length === 0) {
      //             this.getCheckedData();
      //         } else {
      //             //  什么都不做
      //         }
      //     } else if (this.query.checked === false) {
      //         if (this.tableData.length === 0) {
      //             this.getData();
      //         } else {
      //             //  什么都不做
      //         }
      //     }
      // },
      computed: {
          ...mapGetters({
              pageTotal: 'editMenuPageTotal',
              tableData: 'editMenuData',
              query: 'editMenuQuery',
              tagsList: 'tagsList'
          })
      },
      watch: {
          $route: {
              deep: true,
              immediate: true,
              handler(a, b) {
                  console.log(a, b);
                  if (a.name === 'EditMenu' && this.query.checked === true) {
                      if (this.tableData.length === 0) {
                          this.getCheckedData();
                      } else {
                          //  什么都不做
                      }
                  } else if (a.name === 'EditMenu' && this.query.checked === false) {
                      if (this.tableData.length === 0) {
                          this.getData();
                      } else {
                          //  什么都不做
                      }
                  }
              }
          }
      },
      methods: {
          handleChangeStatus(value, index, row) {
              this.$confirm(`确定要${row.status === 0 ? '下线' : '上线'}吗？`, '提示', {
                  type: 'warning'
              })
                  .then(() => {
                      this.changeStatus(value, index, row);
                  })
                  .catch(() => {
                      row.status = row.status === 0 ? 1 : 0;
                      this.SET_EDITMENU_DATA([...this.tableData]);
                  });
          },

          async changeStatus(value, index, row) {
              console.log(value, index, row);
              try {
                  let url = '/playlist/changeStatus';
                  let { data: res } = await this.$http[2].get(url, {
                      params: this.$removeField({
                          id: row.id,
                          status: value
                      })
                  });
                  console.log(res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  this.$message.success({
                      message: res.message,
                      duration: 1500
                  });

                  this.getData();

                  // if (this.query.checked === true) {
                  //     if (this.tableData.length === 0) {
                  //         this.getCheckedData();
                  //     } else {
                  //         //  什么都不做
                  //     }
                  // } else if (this.query.checked === false) {
                  //     if (this.tableData.length === 0) {
                  //     this.getData();
                  //     } else {
                  //         //  什么都不做
                  //     }
                  // }
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          ...mapMutations({
              SET_EDITMENU_FORM: 'SET_EDITMENU_FORM',
              SET_EDITMENU_DATA: 'SET_EDITMENU_DATA',
              SET_EDITMENU_PAGETOTAL: 'SET_EDITMENU_PAGETOTAL',
              SET_EDITMENU_QUERY: 'SET_EDITMENU_QUERY',
              SET_EDITMENU_1_PAGETOTAL: 'SET_EDITMENU_1_PAGETOTAL',
              SET_EDITMENU_QUERY_1: 'SET_EDITMENU_QUERY_1'
          }),
          // handleStatusChange(value) {
          //     console.log(value);
          //     if (value == true) {
          //         this.$set(this.query, 'pageIndex', 1);
          //         this.getCheckedData();
          //     } else {
          //         this.getData();
          //     }
          // },
          handleStatusChange: debounce(function (value) {
              setTimeout(() => {
                  if (value == true) {
                      this.$set(this.query, 'pageIndex', 1);
                      this.getCheckedData();
                  } else {
                      this.$set(this.query, 'pageIndex', 1);
                      this.getData();
                  }
              }, 500);
          }, 1000),

          // handleImport() {},
          handleRefresh() {
              if (this.query.checked) {
                  this.$set(this.query, 'pageIndex', 1);
                  this.getCheckedData();
              } else {
                  this.$set(this.query, 'pageIndex', 1);
                  this.getData();
              }

              // location.reload();
          },
          // handleDelete() {},
          async getCheckedData() {
              try {
                  let _this = this;
                  this.cancelQuest(); //在请求发出前取消上一次未完成的请求；
                  NProgress.start();
                  let url = '/playlist/list';
                  let { data: res } = await this.$http[2].get(url, {
                      headers: {
                          name: localStorage.getItem('roles')
                              ? JSON.parse(localStorage.getItem('roles')).includes('ADMIN') ||
                                JSON.parse(localStorage.getItem('roles')).includes('part-time job2')
                                  ? ''
                                  : localStorage.getItem('ms_username')
                              : ''
                      },
                      cancelToken: new axios.CancelToken(function executor(c) {
                          _this.source = c;
                      }),
                      params: this.$removeField({
                          page: this.query.pageIndex,
                          size: this.query.pageSize,
                          ids: this.query.id ? this.query.id.trim() : this.query.id,
                          name: this.query.name ? this.query.name.trim() : this.query.name,
                          tagName: this.query.tagName ? this.query.tagName.trim() : this.query.tagName,
                          status: this.query.status,
                          createBy: this.query.createBy ? this.query.createBy.trim() : this.query.createBy,
                          editFlag: this.query.checked,
                          excellentFlag: this.query.excellentFlag
                      })
                  });
                  console.log('待审核', res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  if (res.data.content && res.data.content.length > 0) {
                      res.data.content.map((item) => {
                          item.publishTime = this.$dateFormat(item.publishTime, '', '-');
                          item.createTime = this.$dateFormat(item.createTime, '', '-');
                          item.tags = item.tags ? item.tags : [];

                          if (item.tblTags && item.tblTags.length > 0) {
                              item.tblTags.name = '';
                              item.tblTags.map((val) => {
                                  item.tblTags.name += val.name + ',';
                              });
                              item.tblTags.name = item.tblTags.name.slice(0, -1);
                          } else {
                              item.tblTags = [];
                              item.tblTags.name = '';
                          }
                      });

                      this.SET_EDITMENU_DATA(res.data.content);
                      this.SET_EDITMENU_PAGETOTAL(res.data.totalElements);
                      // this.show = true;
                      var tempQuery = { ...this.query };
                      this.$set(tempQuery, 'show', true);
                      this.SET_EDITMENU_QUERY(tempQuery);
                  } else {
                      this.SET_EDITMENU_DATA([]);
                      this.SET_EDITMENU_PAGETOTAL(0);
                      // this.show = true;
                      var tempQuery = { ...this.query };
                      this.$set(tempQuery, 'show', true);
                      this.SET_EDITMENU_QUERY(tempQuery);
                  }

                  NProgress.done();
              } catch (err) {
                  NProgress.done();
                  console.dir(err);
                  // this.$set(this.query, 'checked', true);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          async getData() {
              try {
                  let _this = this;
                  this.cancelQuest(); //在请求发出前取消上一次未完成的请求；
                  NProgress.start();
                  this.disabled = true;
                  let url = '/playlist/list';
                  let { data: res } = await this.$http[2].get(url, {
                      headers: {
                          name: localStorage.getItem('roles')
                              ? JSON.parse(localStorage.getItem('roles')).includes('ADMIN') ||
                                JSON.parse(localStorage.getItem('roles')).includes('part-time job2')
                                  ? ''
                                  : localStorage.getItem('ms_username')
                              : ''
                      },
                      cancelToken: new axios.CancelToken(function executor(c) {
                          _this.source = c;
                      }),
                      params: this.$removeField({
                          page: this.query.pageIndex,
                          size: this.query.pageSize,
                          ids: this.query.id ? this.query.id.trim() : this.query.id,
                          name: this.query.name ? this.query.name.trim() : this.query.name,
                          tagName: this.query.tagName ? this.query.tagName.trim() : this.query.tagName,
                          status: this.query.status,
                          createBy: this.query.createBy ? this.query.createBy.trim() : this.query.createBy,
                          excellentFlag: this.query.excellentFlag,
                          playlistType: 0
                      })
                  });
                  console.log('编辑歌单', res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  if (res.data.content && res.data.content.length > 0) {
                      res.data.content.map((item) => {
                          item.publishTime = this.$dateFormat(item.publishTime, '', '-');
                          item.createTime = this.$dateFormat(item.createTime, '', '-');

                          if (item.tblTags && item.tblTags.length > 0) {
                              item.tblTags.name = '';
                              item.tblTags.map((val) => {
                                  item.tblTags.name += val.name + ',';
                              });
                              item.tblTags.name = item.tblTags.name.slice(0, -1);
                          } else {
                              item.tblTags = [];
                              item.tblTags.name = '';
                          }
                      });
                      this.SET_EDITMENU_DATA(res.data.content);
                      this.SET_EDITMENU_PAGETOTAL(res.data.totalElements);
                      // this.show = false;
                      var tempQuery = { ...this.query };
                      this.$set(tempQuery, 'show', false);
                      this.SET_EDITMENU_QUERY(tempQuery);
                  } else {
                      this.SET_EDITMENU_DATA([]);
                      this.SET_EDITMENU_PAGETOTAL(0);
                      // this.show = false;
                      var tempQuery = { ...this.query };
                      this.$set(tempQuery, 'show', false);
                      this.SET_EDITMENU_QUERY(tempQuery);
                  }
                  NProgress.done();
                  this.disabled = false;
              } catch (err) {
                  console.dir(err);
                  NProgress.done();
                  this.disabled = false;
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          cancelQuest() {
              if (typeof this.source === 'function') {
                  this.source('终止请求'); //取消请求
              }
          },
          // 触发查询按钮
          // handleSearch() {
          //     this.$set(this.query, 'pageIndex', 1);
          //     if (this.query.checked === true) {
          //         this.getCheckedData();
          //     } else {
          //         this.getData();
          //     }
          // },

          handleSearch: debounce(function () {
              this.$set(this.query, 'pageIndex', 1);
              if (this.query.checked === true) {
                  this.getCheckedData();
              } else {
                  this.getData();
              }
          }, 300),

          // 多选操作
          handleSelectionChange(val) {},
          // 审核
          handleChecked(index, row) {
              this.SET_EDITMENU_FORM({});
              this.SET_EDITMENU_1_PAGETOTAL(0);
              this.SET_EDITMENU_QUERY_1({
                  // src: '',
                  pageIndex: 1,
                  pageSize: 10,
                  importName: '',
                  actorImportName: '',
                  albumImportName: '',
                  ids: ''
              });
              // this.SET_EDITMENU_PAGETOTAL(0);
              // this.SET_EDITMENU_QUERY({
              //     show: false,
              //     checked: false,
              //     pageIndex: 1,
              //     pageSize: 10,
              //     id: null,
              //     name: null,
              //     tagName: null,
              //     status: null,
              //     createBy: null,
              //     excellentFlag: null
              // });
              this.$router.replace({
                  // name: 'EditMenu_1',
                  // params: {
                  //     id: row.id,
                  //     e: '1'
                  // }
                  path: '/edit/menu_1',
                  query: {
                      id: row.id,
                      e: 1
                  }
              });

              localStorage.setItem('id_menu', row.id);
              localStorage.setItem('edit_menu_e', 1);
          },
          // 编辑操作
          handleEdit(index, row) {
              this.$handleLock.call(this, index, row, this.edit, '/playlist/lock', row.id);
          },
          edit(index, row) {
              // 这段代码会出现总数为0
              this.SET_EDITMENU_FORM({});
              // this.SET_EDITMENU_1_PAGETOTAL(0);
              // this.SET_EDITMENU_QUERY_1({
              //     // src: '',
              //     pageIndex: 1,
              //     pageSize: 10,
              //     importName: '',
              //     actorImportName: '',
              //     albumImportName: '',
              //     ids: ''
              // });
              // 这段代码会出现总数为0

              localStorage.setItem('id_menu', row.id);
              localStorage.setItem('edit_menu_e', 0);
              this.$router.replace({
                  path: '/edit/menu_1',
                  query: {
                      id: row.id,
                      e: '0'
                  }
              });

              // this.SET_EDITMENU_PAGETOTAL(0);
              // this.SET_EDITMENU_QUERY({
              //     show: false,
              //     checked: false,
              //     pageIndex: 1,
              //     pageSize: 10,
              //     id: null,
              //     name: null,
              //     tagName: null,
              //     status: null,
              //     createBy: null,
              //     excellentFlag: null
              // });
          },
          // async handleEdit(index, row) {
          //     console.log(index, row);
          //     try {
          //         let url = '/playlist/checkEdit';
          //         let { data: res } = await this.$http[2].get(url, {
          //             params: {
          //                 id: row.id
          //             }
          //         });
          //         console.log(res);
          //         if (res.data == true) {
          //             this.$router.replace({
          //                 // name: 'EditMenu_1',
          //                 // params: {
          //                 //     id: row.id,
          //                 //     e: '0'
          //                 // }

          //                 path: '/edit/menu_1',
          //                 query: {
          //                     id: row.id,
          //                     e: '0'
          //                 }
          //             });
          //             row.e = false;
          //             localStorage.setItem('id_menu', row.id);
          //             localStorage.setItem('edit_menu_e', 0);
          //         } else {
          //             this.$message.warning({
          //                 message: '不可编辑',
          //                 duration: 1500
          //             });
          //             row.e = true;
          //         }
          //         // this.tableData = [...this.tableData];
          //         this.SET_EDITMENU_DATA([...this.tableData]);
          //     } catch (err) {
          //         console.dir(err);
          //         this.$message.error({
          //             message: err.message,
          //             duration: 1500
          //         });
          //     }
          // },
          // 分页导航
          handlePageChange(val) {
              this.$set(this.query, 'pageIndex', val);
              // this.SET_EDITMENU_QUERY(this.query);
              if (this.query.checked == true) {
                  this.getCheckedData();
              } else {
                  this.getData();
              }
          },
          handleSizeChange(val) {
              this.$set(this.query, 'pageSize', val);
              // this.SET_EDITMENU_QUERY(this.query);
              if (this.query.checked == true) {
                  this.getCheckedData();
              } else {
                  this.getData();
              }
          }
      }
  };
</script>

<style lang="scss">
  #edit_menu {
      .table-header {
          .cell {
              white-space: nowrap !important;
          }
      }

      .handle-box {
          margin-bottom: 20px;
          .el-form {
              display: grid;
              grid-auto-flow: column;
              justify-content: flex-start;
              .el-form-item {
                  width: 95%;
                  .el-form-item__content {
                      .el-select,
                      .handle-input {
                          width: 100%;
                      }
                  }
              }
          }
      }

      .handle-select {
          width: 120px;
      }

      .handle-input {
          /* width: 300px; */
          width: 69px;
          height: 28px;
          display: inline-block;
      }
      .table {
          width: 100%;
          font-size: 14px;
          .el-input--small {
              .el-input__inner {
                  text-align: left;
                  font-size: 12px;
                  padding-right: 25px;
              }
              .el-input__suffix {
                  right: 0px;
              }
          }
      }
      .red {
          color: #ff0000;
      }
      .mr10 {
          margin-right: 10px;
      }
      .table-td-thumb {
          display: block;
          margin: auto;
          width: 40px;
          height: 40px;
      }
  }
</style>
